package com.syxbbs.forum.controller;

import com.syxbbs.forum.Utils.MD5Utils;
import com.syxbbs.forum.Utils.StringUtils;
import com.syxbbs.forum.Utils.UUID;
import com.syxbbs.forum.common.AppResult;
import com.syxbbs.forum.common.ResultCode;
import com.syxbbs.forum.config.AppConfig;
import com.syxbbs.forum.exception.ApplicationException;
import com.syxbbs.forum.model.User;
import com.syxbbs.forum.services.Impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

//用于返回数据的注释
@Api(tags = "用户接口")
//返回数据控制器
@RestController
//一级路径
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @RequestMapping(value = "/register", produces = "application/json")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") /*@NonNull */String username,
                              @ApiParam("昵称") @RequestParam("nickname") /*@NonNull */String nickname,
                              @ApiParam("密码") @RequestParam("password") /*@NonNull*/ String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") /*@NonNull*/ String passwordRepeat) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)) {
            //controller一般不抛出异常，直接返回错误就行了。
            return AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE);


        }
        if (!password.equals(passwordRepeat)) {
            return AppResult.failure(ResultCode.FAILED_TWO_PWD_NOT_SAME);

        }
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //生成密文
        String salt = UUID.UUID_32();
        user.setSalt(salt);
        String md5salt = MD5Utils.md5salt(password, salt);
        //设置密码
        user.setPassword(md5salt);

        userService.createNormal(user);

        return AppResult.success();


    }

    //新增用户登录的方法
    @RequestMapping(value = "login", produces = "application/json")
    public AppResult login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request) {
        //非空校验
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(username)) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(ResultCode.FAILED_LOGIN.toString());

        }
        //调用登录方法，返回User对象
        User loginer = userService.login(username, password);
        //true表示是否创建新的会话。
        HttpSession session = request.getSession(true);
        //user放到session中
        session.setAttribute(AppConfig.USER_SESSION,loginer);

        //返回结果
        return AppResult.success();


    }

    //从后端返回的数据可以不全部传到前端，可以进行挑选不参加json序列化
    /*@JsonIgnore*/
    @RequestMapping(value = "/info", produces = "application/json")
    public AppResult getUserInfo(HttpServletRequest request, @RequestParam(value = "id", required = false) Long id) {
        //这里的require=false表示可以不传数据,如果用户不传数据，我们就从session里面获取。
        User user = null;
        if (id == null){
            //id为空就要从session中获取用户信息,不主动创建。
            HttpSession session = request.getSession(false);
            //直接进行跳转就行了。
            /*if (session == null || AppConfig.USER_SESSION == null) {
                return AppResult.failure(ResultCode.FAILED_FORBIDDEN);

            }*/
            user = (User) session.getAttribute(AppConfig.USER_SESSION);

        } else {
            user = userService.selectById(id);
        }
        if (user == null) {
            return AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }


    @RequestMapping(value = "/logout",produces = "application/json")
    public AppResult loginout(HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session!=null){
            log.info("退出成功");
            //销毁session
            session.invalidate();

        }
        return AppResult.success("退出成功");


    }

    /*
    *
    *修改个人信息
    * */
    @RequestMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request, @RequestParam(value = "username",required = false) String username,
                                @RequestParam(value = "nickname",required = false)String nickname,
                                @RequestParam(value = "gender",required = false)Byte gender,
                                @RequestParam(value = "email",required = false)String email,
                                @RequestParam(value = "phoneNum",required = false)String phoneNum,
                                @RequestParam(value = "remark",required = false)String remark){


        if (StringUtils.isEmpty(username)&&StringUtils.isEmpty(nickname)&&StringUtils.isEmpty(email)&&StringUtils.isEmpty(phoneNum)&&StringUtils.isEmpty(remark)&&gender==null){
            return AppResult.failure("请输入要修改的内容");
        }
        User updateUser=new User();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setEmail(email);
        updateUser.setGender(gender);
        updateUser.setRemark(remark);
        updateUser.setPhoneNum(phoneNum);
        userService.modifyInfo(updateUser);
        user = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success(user);


    }

    @RequestMapping("modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,@NonNull String oldPassword,
                                    @NonNull String newPassword,
                                    @NonNull String passwordRepeat){
         if (!newPassword.equals(passwordRepeat)){
             log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
             throw new ApplicationException(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
         }
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        //修改密码后销毁session
        if (session!=null) {
            session.invalidate();
        }
        return AppResult.success();

    }




}


